<template >
  <div>
     <div class="form_wrap">
       <el-form inline>
        <el-form-item label="角色名称">
          <el-input v-model="queryData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="queryData.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="状态">
         <el-select style="width:200px;" v-model="queryData.status">
          <el-option value="1" label="正常">正常</el-option>
          <el-option value="0" label="禁用">禁用</el-option>
         </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
            <el-date-picker
              v-model="createTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              :size="size"
            />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button>重置</el-button>
        </el-form-item>
       </el-form>
     </div> 
     <div class="btn_wrap">
      <el-button type="primary" @click='openFlag'>新增</el-button>
      <el-button type="warning">修改</el-button>
      <el-button type="danger">删除</el-button>
      <el-button type="info" @click="exportData">导出</el-button>
      
     </div>
     <div class="table_wrap">
      <el-table :data="roleList">
        <el-table-column label="角色编号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="权限字符" prop="roleKey"></el-table-column>
        <el-table-column label="显示顺序" prop="roleSort"></el-table-column>
        <el-table-column label="状态" >
          <template #default="{row}">
             <el-switch v-model="row.status" 
             :active-value="'1'" :inactive-value="'0'" ></el-switch>
          </template>  
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="操作">
          <template #default="{row}" > 
            <div v-if="row.roleKey!='admin'">
               <el-link type="primary" @click="toEdit(row.roleId)">修改</el-link>
               <el-link type="danger" @click="toDel(row.roleId)" style="margin:0 20px;">删除</el-link>
               <el-link type="primary">更多</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <Pagination v-model:page="queryData.pageNum" 
        v-model:limit="queryData.pagesize"
        @pagination="getList"
        :total="total" ></Pagination>
      </div>
      <!-- 增加弹出层 -->
      <el-dialog title="增加角色" width="50%" v-model="roleFlag" >
        <el-form label-width="100px" :model="formObj" :rules="rules" ref="addForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="formObj.roleName"></el-input>
          </el-form-item>
          <el-form-item prop="roleKey">
            <template #label>
              <div style="display: flex; align-items: center;">
                <el-popover placement="top-start"
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" 
                effect="dark" 
                width="500">
                    <template #reference>
                       <el-icon size="20" >
                          <QuestionFilled  />
                       </el-icon>  
                    </template>
                </el-popover>
                
                 权限字符
              </div>
            </template>
            <el-input v-model="formObj.roleKey"></el-input>
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
           <el-input-number v-model="formObj.roleSort" controls-position="right"></el-input-number>
          </el-form-item>
          <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formObj.status">
                <el-radio lable="正常" value="1">正常</el-radio>
                <el-radio lable="禁用" value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item> 
          <el-form-item label='菜单权限
'>    
                <el-checkbox-group v-model="menuExpand">
                  <el-checkbox v-model="menuFild" @change="toChangeMenu($event)" label="展开/折叠"></el-checkbox>
                  <el-checkbox @change="allMenu($event)"  label="全选/全不选"></el-checkbox>
                  <el-checkbox v-model="formObj.menuCheckStrictly" @change="parentChange" label="父子联动"></el-checkbox>
                </el-checkbox-group>
                <el-tree
                 class="treeboder"
                    style="max-width: 600px"
                    :data="treeData"
                    show-checkbox
                    :default-expand-all="false"
                    :check-strictly="!formObj.menuCheckStrictly"
                    ref="treeRef"
                    @check="getKeys"
                    node-key="id"
                  />
          </el-form-item>
          <el-form-item label="备注"> 
             <el-input type="textarea"  v-model="formObj.remark"></el-input>
          </el-form-item>
          
        </el-form>
          <template #footer>
            <div>
               <el-button type="primary" @click="savaAll">确定</el-button>
               <el-button @click="roleFlag=false">取消</el-button>
            </div>
          </template>
      </el-dialog>  
     </div>
  </div>
</template>
<script setup>
  import {ref,reactive,getCurrentInstance,watch} from 'vue'
import {listRole,addRole,getRole,updateRole,roleMenuTreeselect,delRole} from '@/api/system/role'
import { QuestionFilled } from '@element-plus/icons-vue';
import {treeselect} from '@/api/system/menu' 
import * as  XLSX from 'xlsx'
import {parseTime} from '@/utils/ruoyi'
  let {proxy}=getCurrentInstance();
  console.log(proxy,"全局实例的引用 可以使用上面的方法和属性")
  // app.proxy对象  下面 有$refs $attrs $slots $emit $props $router $route $options $forceUpdate $nextTick $watch $watchEffect
  proxy.sayHello()



  let  createTime=ref('')
  let queryData=reactive({
    pageNum:1,
    pagesize:10,
    roleName:"",
    roleKey:"",
    status:"",
   
    params:{
      beginTime:"",
      endTime:""
    }
  })
  let roleList=ref([])
  let total=ref(0)
  let getList=async ()=>{
    // 处理下 选中的时间 时间公司
    if(createTime.value){              //2025-06-25
      queryData.params["beginTime"]=parseTime(createTime.value[0],"{y}-{m}-{d}");
      queryData.params["endTime"]=parseTime(createTime.value[1],'{y}-{m}-{d}');
    }
  

    // 调用接口获取数据
    console.log(queryData)
    let res=await listRole(queryData)
    console.log(res,"获取角色列表")
    roleList.value=res.rows;
    total.value=res.total;
  } 
  getList()

  // 增加
  
  let roleFlag=ref(false)
  let openFlag=()=>{ //打开弹出层
    roleFlag.value=true
  }
  let treeData=ref([])//菜单树形数据
  let getTree=async ()=>{
    let res=await treeselect();
    console.log(res,"获取菜单树形数据")
    treeData.value=res.data;

  }
  getTree();

  // 增加接口需要的数据
  let formObj=reactive({
    deptCheckStrictly: true, //部门展开
    deptIds: [], //部门ids
    menuCheckStrictly: false,  //菜单是否严格选择 父子联动
    menuIds:[],  //角色能访问的菜单ids
    remark: "" ,// 备注
    roleKey: "" ,// 标识
    roleName: "",//  角色名称
    roleSort: 0 ,//       排序
    status:''  ,//     状态  0 启用  1禁用
  })
  let menuExpand=ref([])//菜单展开 复选框组收集数据
  let menuFild=ref(false)
  // 表单验证
  let rules={
    roleName:[{required:true,message:"请输入角色名称",trigger:"blur"}],
    roleKey:[{required:true,message:"请输入角色标识",trigger:"blur"}],
    roleSort:[{required:true,message:"请输入角色顺序",trigger:"blur"}],
    status:[{required:true,message:"请选择状态",trigger:"blur"}],
  }

  // 收集菜单id 
  let treeRef=ref(null)
  let getKeys=(data,checkedKeys)=>{

    console.log(treeRef.value.getCheckedKeys(),"获取选中的菜单id")
    formObj.menuIds=treeRef.value.getCheckedKeys()
  }
// 展开与折叠的方法
  let toChangeMenu=(e)=>{
    console.log( menuFild.value,"事件触发了吗")
    menuFild.value=!menuFild.value;
      for (let i = 0; i < treeRef.value.store._getAllNodes().length; i++) {
        // 遍历 el-tree 的每个节点，将节点的 expanded 属性设为 true 或 false
        treeRef.value.store._getAllNodes()[i].expanded = e;
      }
  }
  // allMenu 全选与全不选
  let allMenu=(e)=>{
    console.log(e,"全选与全不选")
    //   treeRef.value.setCheckedNodes(数据,true)
    if(e){
      treeRef.value.setCheckedNodes(treeData.value)
    }else{
      treeRef.value.setCheckedNodes([])
    }
  
  }

  // 父子联动
  let parentChange=(e)=>{
    formObj.menuCheckStrictly=e;
  }

  // savaAll 添加和修改
  let savaAll=async ()=>{
      proxy.$refs.addForm.validate(async (valid)=>{
        if(valid){
          if( formObj.roleId){
              let editRes=await updateRole(formObj)
              console.log(editRes,"修改接口")
          }else{
            let res=await addRole(formObj)
            console.log(res,"添加接口")
          }
        
          proxy.$refs.addForm.resetFields();//表单重置
          getList();//获取列表
          roleFlag.value=false //关闭弹出层 
          treeRef.value.setCheckedNodes([])//变为全不选
          formObj.remark=''//备注清空
        }
      })
    
  }
  // 修改回显
  let toEdit=async (roleId)=>{
   
    let res = await getRole(roleId)
    console.log(res, "------------")
    roleFlag.value=true;
    formObj.roleName=res.data.roleName
    formObj.roleKey=res.data.roleKey
    formObj.roleSort=res.data.roleSort
    formObj.status=res.data.status
    formObj.remark=res.data.remark
  
    formObj.roleId=res.data.roleId//修改需要的id
    let menuRes=await roleMenuTreeselect(roleId);
    console.log(menuRes.checkedKeys,"回显--》获取角色菜单树形数据")
    formObj.menuIds=menuRes.checkedKeys;//选中的菜单 [1,2,3,45]

    // setCheckedKeys 通过id数组 回显树形菜单
    treeRef.value.setCheckedKeys(menuRes.checkedKeys)//回显选中的菜单
  }
  // 监听关闭弹出层 清空
  watch(roleFlag,(newVal)=>{
    if(!newVal){
      formObj.roleName=""
      formObj.roleKey=""
      formObj.roleSort=0
      formObj.status=""
      formObj.remark=""
      formObj.menuIds=[]
      formObj.roleId=""//修改需要的id
      treeRef.value.setCheckedNodes([])//变为全不选
    }
    
  })
  // 导出excel表格
  let exportData=()=>{
    // 创建一个工作簿
    let wookbook = XLSX.utils.book_new();
    // 创建一个工作表  数据转为 表格格式
    let worksheet = XLSX.utils.json_to_sheet(roleList.value);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wookbook, worksheet, "角色列表");
    // 将工作簿保存为Excel文件
    XLSX.writeFile(wookbook, "角色列表.xlsx");
   
  }
  // 删除接口
  let toDel=async (roleId)=>{
    let res=await delRole(roleId)
    console.log(res,"删除接口")
    getList()
  }
</script>
<style lang="scss" scoped> 
.form_wrap{
  margin: 20px;
}
.btn_wrap{
  margin: 20px;
}
.treeboder{
  width: 600px;
  border:  1px solid #ccc;
}

</style>